package org.adorsys.aderp.jpa.impl;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class BusinessKeyInfoBuilder {

	public static <T, ID extends Serializable> BusinessKeyInfo<T, ID> buildBusinessKeyInfo(Class<T> klass){		
		
		Field businessKeyField = FieldResolver.extractBusinessKeyField(klass);
		if(businessKeyField==null) return null;
		
		Method businessKeyGetterMethod = FieldResolver.getterMethod(businessKeyField, klass);
		Method businessKeySetterMettod = FieldResolver.setterMethod(businessKeyField, klass);
		
		Map<Field, Method> immutableReaders = new HashMap<Field, Method>();
		Map<Field, Method> immutableWriters = new HashMap<Field, Method>();
		
		List<Field> immutableFields = new ArrayList<Field>();

		immutableFields.addAll(FieldResolver.extractImmutableField(klass));
		
		for (Field field : immutableFields) {
			Method immutableReader = FieldResolver.getterMethod(field, klass);
			if(immutableReader!=null) immutableReaders.put(field,  immutableReader);
			
			Method immutableWriter = FieldResolver.setterMethod(field, klass);
			if(immutableWriter!=null) immutableWriters.put(field, immutableWriter);
		}
		
		Field idField = FieldResolver.extractIdField(klass);
		Method idGetterMethod = FieldResolver.getterMethod(idField, klass);
		Method idSetterMethod = FieldResolver.setterMethod(idField, klass);
		
		Field versionField = FieldResolver.extractVersionField(klass);
		Method versionGetterMethod = FieldResolver.getterMethod(versionField, klass);
		Method versionSetterMethod = FieldResolver.setterMethod(versionField, klass);
		
		return new BusinessKeyInfo<T, ID>(businessKeyField, 
				businessKeyGetterMethod, businessKeySetterMettod, 
				idGetterMethod, idSetterMethod, 
				versionGetterMethod, versionSetterMethod, 
				immutableReaders, immutableWriters, immutableFields);
		
	}
}
